import uuid
from eval_lib.common.exceptions import BadRequestException
from eval_lib.model.base import BaseStruct, CaseParams
from eval_lib.model.const import CASE_PARAMS_STATUS_CREATE
from config import conf


class Cron(BaseStruct):

    KEYS = ["minute", "hour", "day", "month", "week"]

    def init(self, **kwargs):
        cron = kwargs.get("cron", "")
        if not cron:
            raise BadRequestException("cron is empty")
        cron_split = cron.split(" ")
        if len(cron_split) != 5:
            raise BadRequestException("cron format error")
        minute, hour, day, month, week = cron_split
        super().init(minute=minute, hour=hour, day=day, month=month, week=week)

    def __str__(self):
        return f"{self.minute} {self.hour} {self.day} {self.month} {self.week}"

    def is_valid(self):
        try:
            _ = int(self.minute) if self.minute != "*" else "*"
            _ = int(self.hour) if self.hour != "*" else "*"
            _ = int(self.day) if self.day != "*" else "*"
            _ = int(self.month) if self.month != "*" else "*"
            _ = int(self.week) if self.week != "*" else "*"
        except Exception as e:
            raise BadRequestException("cron format error")


class CronJobCreate(BaseStruct):

    KEYS = ["name", "cron", "variables", "branch", "active"]

    def init(self, **kwargs):
        print(kwargs)
        kwargs["cron"] = Cron(cron=kwargs.get("cron", ""))
        kwargs["variables"] = CaseParams(
            uuid=str(uuid.uuid4()), status=CASE_PARAMS_STATUS_CREATE,
            **kwargs.get("variables", {})
        )
        super().init(**kwargs)

    def is_valid(self):
        if not self.name:
            raise BadRequestException("name is required")
        if not self.cron:
            raise BadRequestException("cron is required")
        if not self.branch:
            raise BadRequestException("branch is required")
        if self.active is None:
            raise BadRequestException("active is required")
        self.variables.is_valid()
        self.cron.is_valid()


class CronJobUpdate(BaseStruct):

    KEYS = ["uuid", "name", "cron", "variables", "branch", "active"]


class CronJobDelete(BaseStruct):

    KEYS = ["uuids"]


class CronJobFilter(BaseStruct):

    KEYS = ["uuid", "uuids", "page_size", "page_index"]

    def init(self, **kwargs):
        super().init(**kwargs)
        self.page_size = int(self.page_size) if self.page_size else None
        self.page_index = int(self.page_index) if self.page_index else None
